package com.stylefeng.guns;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.stylefeng.guns.modular.ipmng.dao.BdapWhiteipListMapper;
import com.stylefeng.guns.modular.ipmng.service.IIpWhiteListService;

/**
 * 
 * ClassName: IpSecurityInterceptor
 * 
 * @Description: TODO IP拦截器
 * @author xiongyao
 * @date 2017年11月15日
 */
@Component
public class IpSecurityInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory
			.getLogger(IpSecurityInterceptor.class);

	@Resource
	private BdapWhiteipListMapper mapper;

	@Resource
	private IIpWhiteListService ipservice;

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object obj) throws Exception {
		// TODO Auto-generated method stub
		logger.info("访问用户地址=================" + request.getRemoteAddr());
		// EntityWrapper<BdapWhiteipList> entityWrapper = new
		// EntityWrapper<BdapWhiteipList>();
		// List<BdapWhiteipList> list = mapper.selectWhiteIpList();
		String userIp = request.getRemoteAddr();
		return ipservice.isAllowed(userIp);
		// String[] userRemoteIp = userIp.split("[.]");
		// if (userRemoteIp.length == 1) {
		// return true;
		// }
		// if (list.isEmpty()) {
		// logger.info("白名单为空");
		// return true;
		// } else {
		// for (BdapWhiteipList whiteips : list) {
		// List<String> ips = Arrays.asList(whiteips.getIp().split(","));
		// for (String ip : ips) {
		// String[] ipsplit = ip.split("[.]");
		// for (int i = 0; i < 4; i++) {
		// if (ipsplit[i].equals("*")) {
		// ipsplit[i] = userRemoteIp[i];
		// }
		// }
		// if (userIp.equals(String.join(".", ipsplit))) {
		// logger.info("在白名单中找到用户IP，可以使用本系统");
		// return true;
		// }
		// }
		// }
		// logger.info("在白名单中没有找到用户IP，不可以使用本系统");
		// return false;
		// }
	}

}
